//
//  NewZoneViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2017/3/23.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "NewZoneViewController.h"
#import "UserModel.h"
#import "UIView+XL.h"
#import "ZoneAlertSettingView.h"

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

#define SearchTableViewCellIdentifer @"searchCell"

@interface NewZoneViewController ()<UISearchBarDelegate,MKMapViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) MKCircle *mapCircle;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) CLLocationManager * locationManager;
@property (strong, nonatomic) MKMapView *mapView;
@property (strong, nonatomic) UserModel *userModel;
@property (strong, nonatomic) UIScrollView *belowScrollView;
@property (strong, nonatomic) ZoneAlertSettingView *zoneAlertSettingView;

@property (assign, nonatomic) CGFloat mapCircleRadius;
@property (assign, nonatomic) MapCircleColor mapCircleColor;

@property (strong, nonatomic) CLGeocoder *geocoder;
@property (strong, nonatomic) UITableViewController *searchTableViewController;
@property (strong, nonatomic) UISearchController *searchController;

@property (strong, nonatomic) NSArray *placeMarksArray;

@property (weak, nonatomic) IBOutlet UIView *aboveMapView;
@property (weak, nonatomic) IBOutlet UIView *belowSettingView;
@property (weak, nonatomic) IBOutlet UILabel *radiusLabel;

@end

@implementation NewZoneViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        
        _userModel = [[UserModel alloc]init];
        
    }
    
    return _userModel;
    
}

-(CLGeocoder *)geocoder{
    
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpView];
    
}



#pragma mark 初始化view
-(void)setUpView{
    
    //初始化地图
    [self locationEnable];
    [self setMap];
    
    //搜索栏
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"Search Address...";

    self.navigationItem.titleView = self.searchBar;
    
    //下方设置view
    self.belowScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.belowSettingView.width, self.belowSettingView.height)];
    
    [self.belowSettingView addSubview:self.belowScrollView];
    
    self.belowScrollView.showsVerticalScrollIndicator = NO;
    
    
    
    
    self.zoneAlertSettingView = [[[NSBundle mainBundle]loadNibNamed:@"ZoneAlertSettingView" owner:self options:nil] lastObject];
    self.zoneAlertSettingView.width = [UIScreen mainScreen].bounds.size.width;
    self.zoneAlertSettingView.height = [self.zoneAlertSettingView getSaveButtonMaxY] + 80;
    
    
    [self.zoneAlertSettingView setUpViewForFenceDictionary:_fenceDictionary];
    
    self.belowScrollView.contentSize = CGSizeMake(self.belowSettingView.width, self.zoneAlertSettingView.height);
    
    [self.belowScrollView addSubview:self.zoneAlertSettingView];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 初始化地图

-(void)setMap{
    
    CGFloat mapViewWidth = STATIC_SCREEN_WIDTH;
    
    CGFloat mapViewHeight = (STATIC_SCREEN_HEIGHT - [[UIApplication sharedApplication] statusBarFrame].size.height - self.navigationController.navigationBar.frame.size.height) * 0.65;
    
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, mapViewWidth, mapViewHeight)];
    
    [self.aboveMapView addSubview:self.mapView];
    
    [self.aboveMapView sendSubviewToBack:self.mapView];
    
    self.mapView.delegate = self;
    
    
    
    self.mapView.mapType = MKMapTypeStandard;
    
    
    self.mapCircleColor = MapCircleColorGreen;
    
    self.mapCircleRadius = 2500;
    
    NSString *radiusString = [NSString stringWithFormat:@"Radius:%0.fm",self.mapCircleRadius];
    
    [self.radiusLabel setText:radiusString];
    
    if (_fenceDictionary) {
        
        self.mapView.userTrackingMode = MKUserTrackingModeNone;
        
        [self setUpMapForFenceDictionary:_fenceDictionary];
        
    }else{
        
        self.mapView.userTrackingMode = MKUserTrackingModeFollow;
        
    }
    
}



#pragma mark 判断是否有权限
-(void)locationEnable{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    
    //请求权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
    {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
    }
    
    //试验
    if (status < 3 || ![CLLocationManager locationServicesEnabled]){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"The user is not allowed to turn on the location service" message:@"Please turn on location service" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
                
            }
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        
        
    }
    
}

#pragma mark 画圆
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKCircle class]]) {
        
        
        
        MKCircleRenderer *circle = [[MKCircleRenderer alloc]initWithOverlay:overlay];
//        circle.lineWidth = 1.0;
//        circle.strokeColor = [UIColor redColor];
        
        switch (self.mapCircleColor) {
            case MapCircleColorGreen:
                
                circle.fillColor = [[UIColor greenColor]colorWithAlphaComponent:0.3];
                
                break;
                
            case MapCircleColorRed:
                
                circle.fillColor = [[UIColor redColor]colorWithAlphaComponent:0.3];
                
                break;
                
            case MapCircleColorBlue:
                
                circle.fillColor = [[UIColor blueColor]colorWithAlphaComponent:0.3];
                
                break;
                
            default:
                break;
        }
        
        
        return (MKOverlayView *)circle;
    }
    return nil;
}

#pragma mark region改变时调用
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
    [self addCircleToMapView];
    
}

#pragma mark 添加圈
-(void)addCircleToMapView{
    
    if (self.mapView.overlays) {
        
        [self.mapView removeOverlays:self.mapView.overlays];
        
    }
    
    
    
    self.mapCircle = [MKCircle circleWithCenterCoordinate:self.mapView.region.center radius:self.mapCircleRadius];
    
    //输出地图中心点
    self.zoneAlertSettingView.mapRegion = self.mapView.region;
    
    [self.mapView addOverlay:self.mapCircle];
    
}

#pragma mark 设置半径和颜色
-(void)setUpMapRadius:(CGFloat)radius color:(MapCircleColor)mapCircleColor{
    
    if (radius) {
        self.mapCircleRadius = radius;
    }
    
    if (mapCircleColor) {
        
        self.mapCircleColor = mapCircleColor;
        
    }
    
    [self addCircleToMapView];
    
}

-(void)setUpMapcolor:(MapCircleColor)mapCircleColor{
    
    if (mapCircleColor) {
        
        self.mapCircleColor = mapCircleColor;
        
    }
    
    [self addCircleToMapView];
    
}

-(void)setUpMapRadius:(CGFloat)radius{
    
    NSLog(@"radius %f",radius);
    

    self.mapCircleRadius = radius;

    
    NSString *radiusString = [NSString stringWithFormat:@"Radius:%0.fm",self.mapCircleRadius];
    
    [self.radiusLabel setText:radiusString];
    
    [self addCircleToMapView];
    
}

#pragma mark 点击searchBar
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    
    self.searchTableViewController = [[UITableViewController alloc]initWithStyle:UITableViewStylePlain];
    self.searchTableViewController.tableView.delegate = self;
    self.searchTableViewController.tableView.dataSource = self;
    self.searchTableViewController.tableView.tableFooterView = [[UIView alloc]init];
    
    //searchController
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchTableViewController];
    self.searchController.searchResultsUpdater = self;
    self.searchController.delegate = self;
    self.searchController.searchBar.placeholder = @"Search Address...";
    
//    self.searchTableViewController.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - self.searchController.view.frame.size.height)];
    
    [self presentViewController:self.searchController animated:YES completion:^{
        
        [self.searchBar resignFirstResponder];
        
    }];
    
}


- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    
    [self.geocoder geocodeAddressString:searchController.searchBar.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        
        
        self.placeMarksArray = placemarks;
        
        [self.searchTableViewController.tableView reloadData];
        
    }];
    
}


#pragma mark tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.placeMarksArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CLPlacemark *placemark = self.placeMarksArray[indexPath.row];
    
    NSLog(@"placemark %@",placemark.addressDictionary);
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchTableViewCellIdentifer];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SearchTableViewCellIdentifer];
        
    }
    

        
//    NSArray *place = [placemark.addressDictionary valueForKey:@"FormattedAddressLines"];
//        
//    NSLog(@"place name %@",[place firstObject]);
//        
//    [cell.textLabel setText:[place firstObject]];

    
    [cell.textLabel setText:[placemark.addressDictionary valueForKey:@"Name"]];
    
    
    
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.textLabel.numberOfLines = 0;
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CLPlacemark *placemark = self.placeMarksArray[indexPath.row];
    
    [self.searchController dismissViewControllerAnimated:YES completion:nil];
    
    NSLog(@"location %@",placemark.location);
    
    MKMapCamera *mapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:placemark.location.coordinate fromEyeCoordinate:placemark.location.coordinate eyeAltitude:15000];
    
    [self.mapView setCamera:mapCamera animated:NO];
    
    
    
}

#pragma mark 有数据初始化
-(void)setUpMapForFenceDictionary:(NSDictionary *)fenceDictionary{
    
    NSString *pointsString = [fenceDictionary valueForKey:NC_POINTS];
    
    //zoneType
    int zoneType = [[fenceDictionary valueForKey:NC_ZONE_TYPE] intValue];
    
    if (zoneType == 0) {
        zoneType = 2;
    }
    //radius
    CGFloat radius = [[self getRadiusForPointsString:pointsString]floatValue];
    
    [self setUpMapRadius:radius color:zoneType];
    
    //camera
    CLLocation *centerLocation = [self getCenterPointsForPointsString:pointsString];
    
    MKMapCamera *mapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:centerLocation.coordinate fromEyeCoordinate:centerLocation.coordinate eyeAltitude:15000];
    
    [self.mapView setCamera:mapCamera animated:NO];
    
    //radius string
    NSString *radiusString = [NSString stringWithFormat:@"Radius:%0.fm",self.mapCircleRadius];
    [self.radiusLabel setText:radiusString];
    
    
}

#pragma mark 获取中心点
-(CLLocation *)getCenterPointsForPointsString:(NSString *)pointsString{
    
    if (pointsString.length > 0) {
        
        NSArray *pointArray = [pointsString componentsSeparatedByString:@"_"];
        
        NSArray *centerPointArray = [[pointArray firstObject] componentsSeparatedByString:@","];
        
        double centerLatitude = [[centerPointArray firstObject] doubleValue];
        
        double centerLongitude = [[centerPointArray lastObject] doubleValue];
        
        NSLog(@"points %f,%f",centerLatitude,centerLongitude);
        
        CLLocation *centerLocation = [[CLLocation alloc]initWithLatitude:centerLatitude longitude:centerLongitude];

        return centerLocation;
        
    }

    return nil;
}

#pragma mark 获取半径
-(NSNumber *)getRadiusForPointsString:(NSString *)pointsString{
    
    if (pointsString.length > 0) {
        
        NSArray *pointArray = [pointsString componentsSeparatedByString:@"_"];
        
        NSArray *centerPointArray = [[pointArray firstObject] componentsSeparatedByString:@","];
        
        NSArray *linePointArray = [[pointArray lastObject] componentsSeparatedByString:@","];
        
        double centerLatitude = [[centerPointArray firstObject] doubleValue];
        
        double centerLongitude = [[centerPointArray lastObject] doubleValue];
        
        double lineLatitude = [[linePointArray firstObject] doubleValue];
        
        double lineLongitude = [[linePointArray lastObject] doubleValue];
        
        NSLog(@"points %f,%f_%f,%f",centerLatitude,centerLongitude,lineLatitude,lineLongitude);
        
        CLLocation *centerLocation = [[CLLocation alloc]initWithLatitude:centerLatitude longitude:centerLongitude];
        
        CLLocation *lineLocation = [[CLLocation alloc]initWithLatitude:lineLatitude longitude:lineLongitude];
        
        int radius = [centerLocation distanceFromLocation:lineLocation];
        
        NSLog(@"radius %d",radius);
        
        return @(radius);
        
    }
    
    return nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
